package com.netintech.project.system.controller;

import java.util.List;
import java.util.Map;
import java.util.Objects;

import com.github.pagehelper.PageInfo;
import com.netintech.core.checkWeakPwd.service.SysWeakpasswordService;
import com.netintech.project.system.domain.dto.CommonsDto;
import com.netintech.project.system.domain.dto.UserDTO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import com.netintech.common.constant.UserConstants;
import com.netintech.common.utils.SecurityUtils;
import com.netintech.common.utils.ServletUtils;
import com.netintech.common.utils.StringUtils;
import com.netintech.common.utils.poi.ExcelUtil;
import com.netintech.core.aspectj.lang.annotation.Log;
import com.netintech.core.aspectj.lang.enums.BusinessType;
import com.netintech.core.security.LoginUser;
import com.netintech.core.security.service.TokenService;
import com.netintech.core.web.controller.BaseController;
import com.netintech.core.web.domain.RequestResult;
import com.netintech.core.web.page.TableDataInfo;
import com.netintech.project.system.domain.SysUser;
import com.netintech.project.system.service.SysPostService;
import com.netintech.project.system.service.SysRoleService;
import com.netintech.project.system.service.SysUserService;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 用户信息
 *
 * @author admin
 */
@Slf4j
@RestController
@RequestMapping("system/user")
public class SysUserController extends BaseController {
    @Autowired
    private SysUserService userService;

    @Autowired
    private SysRoleService roleService;

    @Autowired
    private SysPostService postService;


    /**
     * 获取用户列表
     */
    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @GetMapping("/list")
    public TableDataInfo list(SysUser user) {
//        设备分页信息
        setPageParam();
        List<SysUser> list = userService.selectUserList(user);
        return getDataTable(list);
    }

    /**
     * 获取用户列表
     */
//    @PreAuthorize("@ss.hasPermi('system:user:list')")
    @PostMapping("index")
    public RequestResult user(@RequestBody(required = false) UserDTO userDTO) {
        return RequestResult.success(userService.queryPage(userDTO));
    }

    @RequestMapping("toAdd")
    public RequestResult toAddUser() {
        Map<String, Object> result = userService.toAddPage();
        return RequestResult.success(result);
    }


    /**
     * 修改用户页面
     *
     * @return
     */
    @RequestMapping("toUpd")
    public RequestResult toUpdUser(@RequestBody CommonsDto commonsDto) {
        Long id = commonsDto.getId();
        if (id == null) {
            return RequestResult.error("用户id为null");
        }
        Map<String, Object> result = userService.toUpdPage(id);
        return RequestResult.success(result);
    }


    /**
     * 新增用户
     *
     * @param users
     * @return
     */
    @PostMapping("add")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    public RequestResult addUser(@Valid @RequestBody SysUser users) {
        try {
            return userService.addUser(users);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
            return RequestResult.error("新增失败！");
        }
    }

    /**
     * 修改用户
     *
     * @param users
     * @return
     */
    @PostMapping("upd")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    public RequestResult updUser(@Valid @RequestBody SysUser users) {
        RequestResult requestResult = new RequestResult();
        try {
            requestResult = userService.updUser(users);
        } catch (Exception e) {
            e.printStackTrace();
            return RequestResult.error("修改失败！");
        }
        return requestResult;
    }


    @Log(title = "用户管理", businessType = BusinessType.EXPORT)
    @PreAuthorize("@ss.hasPermi('system:user:export')")
    @GetMapping("/export")
    public RequestResult export(SysUser user) {
        List<SysUser> list = userService.selectUserList(user);
        ExcelUtil<SysUser> util = new ExcelUtil<>(SysUser.class);
        return util.exportExcel(list, "用户数据");
    }

    @Log(title = "用户管理", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public RequestResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        List<SysUser> userList = util.importExcel(file.getInputStream());
        String userId = SecurityUtils.getUserIdString();
        String message = userService.importUser(userList, updateSupport, userId);
        return RequestResult.success(message);
    }

    @GetMapping("/importTemplate")
    public RequestResult importTemplate() {
        ExcelUtil<SysUser> util = new ExcelUtil<SysUser>(SysUser.class);
        return util.importTemplateExcel("用户数据");
    }

    /**
     * 根据用户编号获取详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:user:query')")
    @GetMapping(value = {"/", "/{userId}"})
    public RequestResult getInfo(@PathVariable(value = "userId", required = false) Long userId) {
        RequestResult ajax = RequestResult.success();
        ajax.put("roles", roleService.selectRoleAll());
        ajax.put("posts", postService.selectPostAll());
        if (StringUtils.isNotNull(userId)) {
            ajax.put(RequestResult.DATA_TAG, userService.selectUserById(userId));
            ajax.put("postIds", postService.selectPostListByUserId(userId));
            ajax.put("roleIds", roleService.selectRoleListByUserId(userId));
        }
        return ajax;
    }

    /**
     * 新增用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:add')")
    @Log(title = "用户管理", businessType = BusinessType.INSERT)
    @PostMapping
    public RequestResult add(@Validated @RequestBody SysUser user) {
        if (UserConstants.NOT_UNIQUE.equals(userService.checkUserNameUnique(user.getUserName()))) {
            return RequestResult.error("新增用户'" + user.getUserName() + "'失败，登录账号已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return RequestResult.error("新增用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return RequestResult.error("新增用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setCreateBy(SecurityUtils.getUserIdString());
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        return returnResult(userService.insertUser(user));
    }

    /**
     * 修改用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping
    public RequestResult edit(@Validated @RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        if (UserConstants.NOT_UNIQUE.equals(userService.checkPhoneUnique(user))) {
            return RequestResult.error("修改用户'" + user.getUserName() + "'失败，手机号码已存在");
        } else if (UserConstants.NOT_UNIQUE.equals(userService.checkEmailUnique(user))) {
            return RequestResult.error("修改用户'" + user.getUserName() + "'失败，邮箱账号已存在");
        }
        user.setUpdateBy(SecurityUtils.getUserIdString());
        return returnResult(userService.updateUser(user));
    }

    /**
     * 删除用户
     */
    @PreAuthorize("@ss.hasPermi('system:user:remove')")
    @Log(title = "用户管理", businessType = BusinessType.DELETE)
    @RequestMapping("delete")
    public RequestResult remove(@RequestBody CommonsDto commonsDto) {
        Long id = commonsDto.getId();
        if (Objects.equals(1L, id)) {
            return RequestResult.error("管理员不能删除！");
        }
        return returnResult(userService.deleteUserById(id));
    }

    /**
     * 重置密码
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/resetPwd")
    public RequestResult resetPwd(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setPassword(SecurityUtils.encryptPassword(user.getPassword()));
        user.setUpdateBy(SecurityUtils.getUserIdString());
        return returnResult(userService.resetPwd(user));
    }

    /**
     * 状态修改
     */
    @PreAuthorize("@ss.hasPermi('system:user:edit')")
    @Log(title = "用户管理", businessType = BusinessType.UPDATE)
    @PutMapping("/changeStatus")
    public RequestResult changeStatus(@RequestBody SysUser user) {
        userService.checkUserAllowed(user);
        user.setUpdateBy(SecurityUtils.getUserIdString());
        return returnResult(userService.updateUserStatus(user));
    }
}